package com.ltmonitor.server.mina;

import java.util.Collection;
import java.util.Date;

import com.ltmonitor.jt808.service.IGpsConnectionService;
import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.session.IoSessionConfig;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ltmonitor.app.GpsConnection;
import com.ltmonitor.jt808.protocol.JT_0200;
import com.ltmonitor.jt808.protocol.T808Message;
import com.ltmonitor.jt808.service.IMessageProcessService;
import com.ltmonitor.util.StringUtil;

@Service("jt808ServerHandler")
public class JT808ServerHandler extends IoHandlerAdapter implements IJT808ServerHandler {
	private Logger logger = Logger.getLogger(JT808ServerHandler.class);

	@Autowired
	private IMessageProcessService messageProcessService;


	@Autowired
	private IGpsConnectionService gpsConnectionService;

	public void exceptionCaught(IoSession session, Throwable e)
			throws Exception {
		this.logger.info(getSimNo(session) + "发生异常:" + e.getMessage());
	}

	private String getSimNo(IoSession session) {
		return "" + session.getAttribute("simNo");
	}

	@Override
	public GpsConnection getConnection(String simNo) {
		return gpsConnectionService.getConnection(simNo);
	}

	@Override
	public Collection<GpsConnection> getConnections() {
		return gpsConnectionService.getAllConnections();
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		// tm.platform.server.LocalServer.session = session;
		T808Message tm = (T808Message) message;

		// T808Manager.putMsg(tm);
		session.setAttribute("simNo", tm.getSimNo());
		GpsConnection conn = gpsConnectionService.getConnection(session.getId(), tm);
		if (conn != null) {
			conn.setConnected(true);
			messageProcessService.processMsg(tm);
			tm.setPlateNo(conn.getPlateNo());
			if(conn.getPackageNum() == Integer.MAX_VALUE)
			{
				conn.setPackageNum(0);
				conn.setErrorPacketNum(0);
			}

			conn.setPackageNum(conn.getPackageNum() + 1);

			if (tm.getErrorMessage() != null) {
				conn.setErrorPacketNum(conn.getErrorPacketNum() + 1);
			}
			if (tm.getHeader() != null
					&& tm.getHeader().getMessageType() == 0x0200) {
				JT_0200 p = (JT_0200)tm.getMessageContents();
				conn.setLocated(p.isValid());
				conn.setPositionPackageNum(conn.getPositionPackageNum() + 1);
			}
		}

	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		//this.logger
				//.info("SimNo:" + session.getAttribute("simNo") + "发送成功!");
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {

		String simNo = "" + session.getAttribute("simNo");
		if (StringUtil.isNullOrEmpty(simNo) == false) {
			this.gpsConnectionService.closeConnection(simNo);
		}
		session.close(true);
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		IoSessionConfig cfg1 = session.getConfig();
		if (cfg1 instanceof SocketSessionConfig) {
			SocketSessionConfig cfg = (SocketSessionConfig) session.getConfig();
			// ((SocketSessionConfig) cfg).setReceiveBufferSize(4096);
			cfg.setReceiveBufferSize(2 * 1024 * 1024);
			cfg.setReadBufferSize(2 * 1024 * 1024);
			cfg.setKeepAlive(true);
			// if (session.== TransportType.SOCKET) {
			// ((SocketSessionConfig) cfg).setKeepAlive(true);
			((SocketSessionConfig) cfg).setSoLinger(0);
			((SocketSessionConfig) cfg).setTcpNoDelay(true);
			((SocketSessionConfig) cfg).setWriteTimeout(10000);
		}

	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus idle)
			throws Exception {
		this.logger.error(getSimNo(session) + "连接空闲，将关闭");
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
	}

	@Override
	public void setMessageProcessService(
			IMessageProcessService messageProcessService) {
		this.messageProcessService = messageProcessService;
	}

	@Override
	public IMessageProcessService getMessageProcessService() {
		return messageProcessService;
	}
}
